package com.onec.service.api.utils;


import com.onec.service.api.enums.ResultCodeEnum;
import com.onec.service.api.exception.BaseException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author yangzhongying
 * @date 2019/12/3 17:10
 * @see ValidatorUtils
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws BaseException
     */
    public static void validateEntity(Object object, Class<?>... groups) throws BaseException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint =
                    constraintViolations.iterator().next();
            throw new BaseException(ResultCodeEnum.FAILED.getCode(), constraint.getMessage());
        }
    }


    public static void gatewayValidateEntity(Object object, Class<?>... groups) throws BaseException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint =
                    constraintViolations.iterator().next();
            throw new BaseException(ResultCodeEnum.FAILED.getCode(), constraint.getMessage());
        }
    }
}
